package com.gemalto.Kryptik.Gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.gemalto.Kryptik.Util.*;


public class DetachableTabbedPane extends JTabbedPane {

	private PopupMenu popup;
	private IniFiles ini;
	
	public DetachableTabbedPane() {
		super();
		ini = Util.getIni();
		popup = new PopupMenu(this);
		addMouseListener( new MouseAdapter(){
			public void mouseReleased(MouseEvent e){
    	    			if (e.isPopupTrigger()) {
					popup.setIndex(getSelectedIndex());
            				popup.show(e.getComponent(),e.getX(), e.getY());
            			}
			} }
		);
	}


	// grabs window's size and position and stores it into INI file
	private void storePosition(JFrame g, String title){
		int x = (int)g.getLocation().getX();
		int y = (int)g.getLocation().getY();
		int w = (int)g.getSize().getWidth();
		int h = (int)g.getSize().getHeight();

		ini.setValue("GUI_"+title,"X", x); //((int)g.getLocation().getX())):
		ini.setValue("GUI_"+title,"Y", y); //((int)g.getLocation().getY())):
		ini.setValue("GUI_"+title,"W", w);
		ini.setValue("GUI_"+title,"H", h);
	}



	public void insertTab(String title, Icon icon, Component component, String tip, int index){
		JPanel wrapperPanel = null;

		// Wrap the component
		if (component!=null){
			wrapperPanel = new JPanel();
			wrapperPanel.setLayout(new javax.swing.BoxLayout(wrapperPanel, 1));
			wrapperPanel.add(component);
		}
		super.insertTab(title,icon,wrapperPanel,tip,index);
	}



	public Component getWrappedComponentAt(int index){
		JPanel wrapperPanel = (JPanel)super.getComponentAt(index);

		// Unwrap the component
		if (wrapperPanel!=null){
			Component tab = wrapperPanel.getComponent(0);
			return tab;
		} else {
			return null;
		}
	}


	public void undockTab(final int index) {
		final String title = getTitleAt(index);
		final ImageIcon icon = (ImageIcon)getIconAt(index);
		final Component panel = getWrappedComponentAt(index);
		final JFrame frame = new JFrame(title);
		frame.setIconImage(icon.getImage());

		removeTabAt(index);
		frame.getContentPane().add(panel);

		frame.addWindowListener( new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				storePosition(frame,title);
				insertTab(title,icon,panel, null, index);
			}
		});

//		frame.pack();
//		frame.show();

		// Resize the window according to last used values
		frame.setBounds(ini.getIntValue("GUI_"+title,"X"), ini.getIntValue("GUI_"+title,"Y"),
				ini.getIntValue("GUI_"+title,"W"),ini.getIntValue("GUI_"+title,"H")
		);
		frame.validate();
		frame.show();
	}
}
